package com.zy.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 张宇
 * @date 2021/6/9 11:44
 */
@Slf4j
@Component
public class MessageHandler extends TextWebSocketHandler
{

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final Map<Long, WebSocketSession> SESSIONS = new HashMap<>();

    @Override
    public void handleTextMessage(WebSocketSession webSocketSession, TextMessage textMessage) throws Exception
    {
        Long uid = (Long)webSocketSession.getAttributes().get("uid");

        String[] message = (textMessage.getPayload()).split("&");
        String[] toIdString = message[0].split("=");
        Long toId = Long.parseLong(toIdString[1]);
        String[] msgString = message[1].split("=");
        String msg = msgString[1];

        //判断to用户是否在线
        WebSocketSession toSession = SESSIONS.get(toId);
        if(toSession != null && toSession.isOpen())
        {
            toSession.sendMessage(new TextMessage(msg));//具体格式需要和前端对接
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception
    {
        Long uid = (Long)session.getAttributes().get("uid");
        SESSIONS.put(uid,session);//将当前用户的session放置到map中，后面会使用相应的session通信
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception
    {
        log.debug("连接已经断开!");
    }

}
